package auth

import (
	"context"
	"go.uber.org/zap"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	authpb "serve/auth/api/gen/v1"
	"serve/auth/dao"
	"time"
)

type OpenIDResolver interface {
	Resolve(code string) (string, error)
}

//TokenGenerator 生成token
type TokenGenerator interface {
	GenerateToken(accountID string, expire time.Duration) (string, error)
}

type Service struct {
	OpenIDResolver OpenIDResolver
	Mongo          *dao.Mongo
	Logger         *zap.Logger
	TokenGenerator TokenGenerator
	TokenExpire    time.Duration
}

func (s *Service) Login(c context.Context, req *authpb.LoginRequest) (*authpb.LoginResponse, error) { // 实现登陆
	openID, err := s.OpenIDResolver.Resolve(req.Code) // 获取open id
	s.Logger.Info("openID:", zap.String("openID", openID))

	if err != nil {
		s.Logger.Error("s.OpenIDResolver.Resolve(req.Code) err", zap.Error(err))
		return nil, status.Errorf(codes.Unavailable, "获取openid失败 %v", err)
	}

	accountID, err := s.Mongo.ResolveAccountID(c, openID) // 获取根据openID获取accountid
	if err != nil {
		s.Logger.Error("s.Mongo.ResolveAccountID(c, openID) err", zap.Error(err))
		return nil, status.Errorf(codes.Internal, "")
	}

	token, err := s.TokenGenerator.GenerateToken(accountID.String(), s.TokenExpire) // 创建tooken
	if err != nil {
		s.Logger.Error("s.TokenGenerator.TokenGeneToken(accountID) err", zap.Error(err))
		return nil, status.Errorf(codes.Internal, "")
	}

	return &authpb.LoginResponse{
		AccessToken: token,
		ExpiresIn:   int32(s.TokenExpire.Seconds()),
	}, nil
}
